﻿using System;
using EPiServer;
using EPiServer.Framework;
using EPiServer.Web;
using TemplateFoundation.Configuration;
using TemplateFoundation.Core;
using TemplateFoundation.PageTypes;

namespace TemplateFoundation.EventHandlers
{
    /// <summary>
    /// Used to clear the page cache for articles
    /// </summary>
    [InitializableModule]
    [ModuleDependency(typeof(PageTypeBuilder.Initializer))]
    public class CacheManagement : IInitializableModule
    {
        private bool _creatingPageEventAttached = false;

        void ManageCache(object sender, PageEventArgs e)
        {
            // Clear blog caches whenever an article is published
            if(e.Page is ArticlePageBase)
            {
                // Clear cache objects depending on the blog
                DataFactoryCache.RemoveListing(Settings.Instance.NewsContainer);

                // Clear cache objects depending on the year container
                DataFactoryCache.RemoveListing(e.Page.ParentLink.GetPage().ParentLink);

                // Clear cache objects depending on the month container
                DataFactoryCache.RemoveListing(e.Page.ParentLink);
            }
        }

        #region IInitializableModule Members

        /// <summary>
        /// Initializes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Initialize(EPiServer.Framework.Initialization.InitializationEngine context)
        {
            if (!_creatingPageEventAttached)
            {
                DataFactory.Instance.PublishedPage+=ManageCache;
            }

            _creatingPageEventAttached = true;
        }

        /// <summary>
        /// Preloads the specified parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        public void Preload(string[] parameters) { throw new NotImplementedException(); }

        /// <summary>
        /// Uninitializes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Uninitialize(EPiServer.Framework.Initialization.InitializationEngine context)
        {
            if (_creatingPageEventAttached)
            {
                DataFactory.Instance.PublishedPage-=ManageCache;
            }
        }

        #endregion
    }
}
